using CoreManager.Common;
using CoreManager.Core.Caching;
using Masuit.Tools.Strings;
using System;
using System.IO;

namespace CoreManager.Services.Captcha
{
    /// <summary>
    /// 验证码服务
    /// </summary>
    public class CaptchaService : ICaptchaService
    {
        private readonly ICacheService _cacheService;
        private readonly Random _random;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cacheService">缓存服务</param>
        public CaptchaService(ICacheService cacheService)
        {
            _cacheService = cacheService;
            _random = new Random();
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">验证码长度</param>
        /// <returns>验证码结果</returns>
        public CaptchaResult GenerateCaptcha(int length = 4)
        {
            // 生成随机验证码
            var captchaCode = CaptchaGenerator.GenerateRandomCode(length);
            //string captchaCode = ValidateCode.CreateValidateCode(length);

            // 生成唯一请求ID
            var requestId = CaptchaGenerator.GenerateRequestId();
            
            // 将验证码存入缓存 - 使用公共常量
            _cacheService.Set(CacheConstants.GetCaptchaKey(requestId), captchaCode, CacheConstants.CAPTCHA_EXPIRY);

            // 生成验证码图片
            var captchaImage = CaptchaGenerator.GenerateCaptchaImage(captchaCode);
            //byte[] captchaImage  = captchaCode.CreateValidateGraphic().ToArray();
            return new CaptchaResult
            {
                RequestId = requestId,
                CaptchaImage = Convert.ToBase64String(captchaImage),
                ExpiresAt = DateTime.Now.Add(CacheConstants.CAPTCHA_EXPIRY) // 使用公共常量计算过期时间
            };
        }

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="requestId">请求ID</param>
        /// <param name="captchaCode">用户输入的验证码</param>
        /// <returns>验证结果</returns>
        public bool ValidateCaptcha(string requestId, string captchaCode)
        {
            if (string.IsNullOrEmpty(requestId) || string.IsNullOrEmpty(captchaCode))
            {
                return false;
            }

            // 从缓存中获取验证码 - 使用公共常量
            var storedCaptcha = _cacheService.Get<string>(CacheConstants.GetCaptchaKey(requestId));
            
            if (string.IsNullOrEmpty(storedCaptcha))
            {
                return false;
            }

            // 验证成功后，删除缓存中的验证码（一次性使用） - 使用公共常量
            _cacheService.Remove(CacheConstants.GetCaptchaKey(requestId));
            
            // 不区分大小写比较
            return string.Equals(storedCaptcha, captchaCode, StringComparison.OrdinalIgnoreCase);
        }

       
    }
}